<template>
    <div class="sysmnews">
        <!-- <h2>系统新闻管理</h2> -->
        <div class="title">
          <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/sysout/sysoutshouye' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>新闻资讯</el-breadcrumb-item>
            <el-breadcrumb-item>新闻资讯管理</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="header">
          <el-input @change="search" v-model="input" placeholder="根据新闻标题、新闻内容进行搜索"></el-input>
          <el-button type="primary">查询</el-button>
          <el-button type="primary">删除</el-button>
        </div>
        <div class="wrapper">
          <el-table :data="tableData" style="width: 100%" border stripe height="700">
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column prop="newsId" label="新闻id" width="80"></el-table-column>
            <el-table-column prop="adminName" label="管理员名" width="80"></el-table-column>
            <el-table-column prop="newsTitle" label="新闻标题"></el-table-column>
            <el-table-column prop="newsContent" label="新闻内容" width=280></el-table-column>
            <el-table-column prop="newsImg" label="图片">
              <template v-slot:default="scope">
                <el-image :src="scope.row.newsImg" style="height:60px;"/>
              </template>
            </el-table-column>
            <el-table-column prop="newsTime" label="发送时间" width=150></el-table-column>
            <el-table-column label="操作" width="240" fixed="right">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  @click="handleClick(scope.row)">查看</el-button>
                <el-button
                  size="mini"
                  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </template>
          </el-table-column>
          </el-table>
        </div>
        <!-- 弹框 -->
        <el-dialog
          title="更新新闻信息"
          :visible.sync="dialogVisible"
          width="50%"
          :before-close="handleClose">
          <!-- <span>这是一段信息</span> -->
          <!-- 弹框内容区域 -->
            <el-form :model="newsForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
              <el-form-item label="新闻标题" prop="newsTitle" required>
                <el-input v-model="newsForm.newsTitle"></el-input>
              </el-form-item>
              <!-- <el-tooltip class="item" effect="dark" content="上传一张主要图片" placement="bottom-start">
                <el-form-item label="商品图片" prop="goodsImg" required>
                  <el-button type="primary" @click="dialogVisibleImg = true">上传图片</el-button>
                  <img v-if="goodsForm.goodsImg" :src="goodsForm.goodsImg" height="100px" style="margin:10px;display:inline-block" alt="">
                </el-form-item>
              </el-tooltip> -->
              <el-form-item label="新闻图片" prop="newsTitle" required>
                <el-button type="primary" @click="getImg">点击获取用户传过来的图片</el-button>
                <img v-if="newsForm.newsImg" :src="newsForm.newsImg" alt="" style="height:100px">
              </el-form-item>
              <el-form-item label="发布时间" required>
                <!-- <el-date-picker type="date" placeholder="选择日期" v-model="goodsForm.subTime" style="width: 30%;"></el-date-picker> -->
                 <el-col :span="11">
                    <el-form-item prop="date1">
                      <el-date-picker type="date" placeholder="选择日期" v-model="date1" style="width: 100%;"></el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col class="line" :span="2">:</el-col>
                  <el-col :span="11">
                    <el-form-item prop="date2">
                      <el-time-picker placeholder="选择时间" value-format="HH:mm:ss" v-model="date2" style="width: 100%;"></el-time-picker>
                    </el-form-item>
                  </el-col>
              </el-form-item>
              <!-- 富文本编辑//官网https://www.wangeditor.com/doc/
                使用：
                1、安装npm i wangeditor
                2、引入 import E from "wangeditor"
                3、使用
                  this.editor = new E("#main")
                  this.editor.create          
                  常用配置：
                  1、清空内容
                    editor.txt.clear()  清空编辑器内容
                  2、设置内容
                    editor.txt.html('') 获取html
                  3、配置菜单
                    1、onchange回调函数

               -->
              <el-form-item label="新闻内容" prop="newsContent" style="z-index: 100;" required>
                <WangEditor ref="myEditor" @sendEditor="sendEditor"/>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="getSubmitTime();submitForm('ruleForm')">确定更新</el-button>
                <el-button @click="clearForm()">重置</el-button>
              </el-form-item>
            </el-form>


          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>

<script>
import axios from 'axios'
export default {
    name:'SysMnews',
    data() {
      return {
        input: "",
        tableData: [],
        allData:[],
        dialogVisible:false,
        date1:'',
        date2:'',
        newsForm:{
            newsTitle:'',
            newsContent:'',
            newsImg:'',
            newsTime:'',
        },
        rules: {//element组件校验规则
          newsTitle: [
            { required: true, message: '请输入新闻标题', trigger: 'blur' },
            { min: 4, max: 255, message: '长度在 4 到 255 个字符', trigger: 'blur' }
          ],
        },
      };
    },
    mounted() {
      this.getAllNews()
    },
    methods: {
      clearForm(){
        // 清空表单
        // this.$refs.ruleForm.resetFields()
        // 单独清空富文本编辑器
        this.$refs.myEditor.editor.txt.clear()
        this.date1 = ''
        this.date2 = ''
        // this.newsForm.newsImg = ''
        this.newsForm = {
            newsTitle:'',
            newsContent:'',
            newsImg:'',
            newsTime:'',
        }
      },
      // 更新发布新闻的资讯
      submitForm(formName){
        console.log(this.$refs[formName])
        this.$refs[formName].validate((valid)=>{
          if(valid){
            axios.get("http://localhost:8080/api/updateNews/updateNewslist",{
              params:{
                adminName:this.newsForm.adminName,
                newsTitle:this.newsForm.newsTitle,
                newsContent:this.newsForm.newsContent,
                newsImg:this.newsForm.newsImg,
                newsTime:this.newsForm.newsTime,
                newsId:this.newsForm.newsId
              }
            }).then(
              res=>{
                this.$message({
                  message:'新闻更新成功',
                  type:'success'
                })
                this.clearForm()
              },
              error=>{
                console.log("b",error.message)
              }
            )
            console.log("获取输入信息",this.newsForm)
          }else{
            console.log("提交错误")
            return false
          }
        })
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
            this.clearForm()
          })
          .catch(_ => {});
      },
      getSubmitTime(){
        var data = this.formatDateTime(this.date1)
        this.newsForm.newsTime = data + ' ' + this.date2
        // this.newsForm.newsTime = String(this.date1).slice(0,15) + String(this.date2).slice(15,24)
        // console.log(this.goodsForm.subTime)
      },
      // 时间转换
      formatDateTime (date) {
        var date = new Date(date)
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        // return y + '-' + m + '-' + d+' '+h+':'+minute;
        return y + '-' + m + '-' + d
      },
      // 接收wangeditor文本数据
      sendEditor(val){
        this.newsForm.newsContent = val
        // console.log("222",this.goodsForm.goodsContent)
      },
      // 获取用户传的图片地址
      getImg(){
        console.log(this.$store.state.user.usersubgoods)
        for(var i=0;i<this.$store.state.user.usersubgoods.length;i++){
          if(this.newsForm.newsTitle.indexOf( this.$store.state.user.usersubgoods[i].goodsName) != -1){
            this.newsForm.newsImg = this.$store.state.user.usersubgoods[i].goodsImg
          }
        }
        if(this.newsForm.newsImg==''){
          alert("请给你发布的竞拍商品新闻标题认真命名(注意包含竞拍名)")
        }
      },
        //  获取所有新闻
      getAllNews(){
            axios.get("http://localhost:8080/api/getAllNewsList/getAllNews",{
              params:{
                id:1
              }
            }).then(
              res=>{
                // this.tableData = res.data
                for(var i= 0;i<res.data.length;i++){
                    var tem = Number(String(res.data[i].newsTime).slice(11,13))+8
                    var d = tem%24 > 10? tem%24 :'0'+tem%24
                    res.data[i].newsTime = String(res.data[i].newsTime).slice(0,10)+ ' ' +d + String(res.data[i].newsTime).slice(13,19)
                    // state.usersubgoods.push(value [i])
                    this.allData = res.data
                    this.tableData = this.allData
                }
                console.log("999",res)
                console.log(this.tableData)

              },
              error=>{
                console.log("88",error.message)
              }
            )
      },
      // 删除事件
      handleDelete(index,row){
            console.log("删除行数据为：",index,row,row.newsId)
            this.$confirm('此操作将永久删除该新闻资讯, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              // 执行删除操作--执行删除数据库操作--请求接口
                axios.get("http://localhost:8080/api/deleteNews/deleteNewslist",{
                  params:{
                    id:row.newsId
                  }
                }).then(
                  res=>{
                    if(res.data.status == 200){
                      this.$message({
                        type: 'info',
                        message: '删除成功'
                      }); 
                      // 视图更新
                      this.$router.go(0)
                    }
                  },
                  error=>{
                    console.log("88",error.message)
                  }
                )
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              });          
            });
      },
      // 查看事件
      handleClick() {

      },
      // 编辑事件---更新新闻
      handleEdit(index,row){
        this.dialogVisible = true
        // 将该行数据放入form表中
        this.newsForm = row
        console.log("该行的数据为",this.newsForm)
        // 设置富文本的数据内容
        this.$nextTick(()=>{//数据更新之后还要继续对这个里面的数据进行操作
          this.$refs.myEditor.editor.txt.html(row.newsContent)
          console.log("this.$refs.myEditor",this.$refs.myEditor,this.$refs.myEditor.editor.txt.html(row.newsContent))
        })
      },

      // 查找事件
       search(val){
          console.log("搜索了----",val,this.allData[0].userId)
          this.tableData = []
          if(val == ' '){
            this.tableData = this.allData
          }else{
            for(var i=0;i<this.allData.length;i++){
              if(this.allData[i].newsTitle.indexOf(val) !==-1 || this.allData[i].newsContent.indexOf(val) !==-1){
              // if(this.allData[i].goodsName.indexOf(val) !==-1){
                this.tableData.push(this.allData[i])
              }
            }
            if(this.tableData == ''){
              alert("未找到你想要搜索的竞拍商品")
            }
          }
          console.log("查询结果为",this.tableData)
        }
    },
}
</script>

<style lang="less" scoped>
.sysmnews {
  margin: 20px;
  width: 95%;

    .title{
      width: 95%;
      padding: 10px;
      background: #fff;
      border: 1px solid #eee;
      margin-bottom: 20px;
    }
    .header {
      display: flex;
      margin-bottom: 10px;
      button {
        margin-left: 20px;
      }
    }
}
.line{
    text-align: center;
}
</style>